<template>
	<div>
		<!-- 查询区 -->
		<div class="card" style="margin-bottom: 5px">
			<el-input
				style="width: 240px; margin-right: 10px"
				v-model="data.search"
				placeholder="请输入名称查询"
				prefix-icon="Search"
			/>
			<el-button type="primary" @click="page">查询</el-button>
			<el-button type="warning" @click="reset">重置</el-button>
		</div>
		
		<!-- 操作按钮 -->
		<div class="card" style="margin-bottom: 5px">
			<el-button type="primary" @click="add">新 增</el-button>
			<el-button type="warning" @click="deleteBatch">批量删除</el-button>
		</div>
		
		<!-- 表格 -->
		<div class="card" style="margin-bottom: 5px">
			<el-table
				:data="data.tableData"
				style="width: 100%"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55" />
				<el-table-column label="封面">
					<template #default="scope">
						<div class="image-preview-wrapper">
							<el-image
								:src="scope.row.img"
								fit="cover"
								style="width: 60px; height: 60px; border-radius: 4px;cursor: pointer"
								preview-teleported
								@click="openPreview(scope.row.img)"/>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="name" label="书籍名" />
				<el-table-column prop="author" label="作者" />
				<el-table-column prop="price" label="价格" />
				<el-table-column prop="time" label="创建时间" />
				<el-table-column fixed="right" label="操作">
					<template #default="scope">
						<el-button type="primary" @click="update(scope.row)">编辑</el-button>
						<el-button type="danger" @click="del(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			
			<!-- 分页 -->
			<div style="margin-top: 15px">
				<el-pagination
					v-model:current-page="data.pageNum"
					v-model:page-size="data.pageSize"
					:page-size="[5, 10, 15, 20]"
					background
					layout="prev, pager, next, jumper"
					:total="data.total"
					@size-change="page"
					@current-change="page"
				/>
			</div>
		</div>
		
		<!-- 弹窗组件复用：新增或编辑 -->
		<BookDialog
			@close:dialogVisible="val => data.dialogFormVisible = val"
			v-model:dialogFormVisible="data.dialogFormVisible"
			:mode="data.dialogMode"
			:form="data.dialogForm"
			:disabled-fields="data.disabledFields"
			@submit-success="handleSubmit"
		/>
		
		
		<!-- 图片预览组件 -->
		<el-image-viewer
			v-if="previewVisible"
			:url-list="previewList"
			@close="previewVisible = false"
		/>
	</div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBookList, addBook, updateBook, deleteBook, deleteBooks } from '@/api/book.js'
import BookDialog from '@/views/page/components/BookDialog.vue'

const data = reactive({
	search: null,
	tableData: [],
	pageNum: 1,
	pageSize: 5,
	total: 0,
	dialogFormVisible: false,
	dialogMode: 'add',
	dialogForm: {},
	disabledFields: [],
	selectedRows: []
})

// 预览相关
const previewVisible = ref(false)
const previewList = ref([])

const openPreview = (url) => {
	previewList.value = [url]
	previewVisible.value = true
}

// 分页查询
const page = () => {
	getBookList({
		pageNum: data.pageNum,
		pageSize: data.pageSize,
		search: data.search
	}).then(res => {
		data.tableData = res.data.records
		data.total = res.data.total
	})
}

onMounted(() => page())

// 新增按钮
const add = () => {
	data.dialogMode = 'add'
	data.dialogForm = { name: '', author: '', price: '', img: '' }
	data.disabledFields = []
	data.dialogFormVisible = true
}

// 编辑按钮
const update = (row) => {
	data.dialogMode = 'edit'
	data.dialogForm = { ...row }  // 一定要浅拷贝，避免引用问题
	data.disabledFields = []
	data.dialogFormVisible = true
}

// 单条删除
const del = (id) => {
	ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		deleteBook(id).then(() => {
			ElMessage.success('删除成功')
			page()
		})
	}).catch(() => {})
}

// 多选变化时更新已选 ID 列表
const handleSelectionChange = (val) => {
	data.selectedRows = val.map(row => row.id)
}

// 批量删除
const deleteBatch = () => {
	if (!data.selectedRows.length) {
		ElMessage.warning('请先选择要删除的记录')
		return
	}
	ElMessageBox.confirm(`确定要批量删除选中的 ${data.selectedRows.length} 条记录吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		deleteBooks(data.selectedRows).then(() => {
			ElMessage.success('批量删除成功')
			data.selectedRows = []
			page()
		})
	}).catch(() => {})
}

// 提交表单（新增或编辑）
const handleSubmit = (form) => {
	const action = form.mode === 'add' ? addBook : updateBook
	action(form).then(() => {
		ElMessage.success(form.mode === 'add' ? '新增成功' : '更新成功')
		data.dialogFormVisible = false
		page()
	}).catch(() => {
		ElMessage.error('提交失败')
	})
}

// 重置查询
const reset = () => {
	data.search = null
	page()
}
</script>
